package com.stormkai.reflect;

import java.lang.reflect.Method;

/**
 * 通过跳过安全检查，提高反射效率
 * 三种执行方法的效率差异比较
 * @author yangkaid
 *
 */
public class Demo6 {
	
	public static void test1() {
		User user = new User();
		
		long startTime = System.currentTimeMillis();
		
		for (int i = 0; i < 1000000000L; i++) {
			user.getName();
		}
		
		long endTime = System.currentTimeMillis();
		
		System.out.println("普通方法调用，执行10亿次，耗时："+(endTime - startTime)+"ms");
	}
	
	public static void test2() throws Exception {
		User user = new User();
		Class clazz = user.getClass();
		Method m = clazz.getDeclaredMethod("getName", null);
		
		long startTime = System.currentTimeMillis();
		
		for (int i = 0; i < 1000000000L; i++) {
			m.invoke(user, null);
		}
		
		long endTime = System.currentTimeMillis();
		
		System.out.println("反射动态方法调用，执行10亿次，耗时："+(endTime - startTime)+"ms");
		
	}
	
	public static void test3() throws Exception {
		User user = new User();
		Class clazz = user.getClass();
		Method m = clazz.getDeclaredMethod("getName", null);
		m.setAccessible(true); //不需要执行访问安全检查
		
		long startTime = System.currentTimeMillis();
		
		for (int i = 0; i < 1000000000L; i++) {
			m.invoke(user, null);
		}
		
		long endTime = System.currentTimeMillis();
		
		System.out.println("反射动态方法调用，跳过安全检查，执行10亿次，耗时："+(endTime - startTime)+"ms");
		
	}

	public static void main(String[] args) throws Exception {
		test1();
		test2();
		test3();

	}

}
